package de.hauck.rtmidlet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;

import de.hauck.rtmidlet.model.Configuration;
import de.hauck.rtmidlet.model.StockBean;
import de.hauck.rtmidlet.model.StockStore;
import de.hauck.rtmidlet.utils.Utils;
import de.hauck.rtmidlet.views.FormConfig;
import de.hauck.rtmidlet.views.FormStockMaintainMenu;

public class FileSystemExportThread implements Runnable {
	static Configuration c;
	StockStore _myStore;
	//static RTMidlet _main;
	FormStockMaintainMenu _fm;
	FormConfig _fc;
	private int _type;

	public FileSystemExportThread(StockStore myStore,
			FormStockMaintainMenu fm, int type) {
		_myStore = myStore;
		//_main = rtmidlet;
		_fm = fm;
		_type = type;
		new Thread(this).start();
	}
	public FileSystemExportThread(FormConfig fc, int type) {
		_fc = fc;
		_type = type;
		new Thread(this).start();
	}

	public void run() {
		Enumeration drives = FileSystemRegistry.listRoots();
		System.out.println("The valid roots found are: ");
		while (drives.hasMoreElements()) {
			String root = (String) drives.nextElement();
			System.out.println("\t" + root);
		}

		if (_type == 1)
			exportStocksToCSV();
		else if (_type == 2)
			exportConfigToCSV();
	}

	protected void exportStocksToCSV() {
		OutputStream os = null;
		FileConnection fileCon = null;
		// String url = c.exportURL;
		String url = "file:///" + Configuration.exportPath + "RTMidlet.csv";
		try {
			Connection logCon = Connector.open(url, Connector.READ_WRITE);
			fileCon = (FileConnection) logCon;
			if (fileCon == null)
				throw new IOException("Couldn't open url " + url);
			if (!fileCon.exists()) {

				fileCon.create();
				System.out.println("writable: " + fileCon.canWrite());
			} else {
				fileCon.truncate(0);
				System.out.println("truncate: " + fileCon.getPath());
			}

			os = fileCon.openOutputStream();// openOutputStream();
			byte[] byte_array = "# data exported in format: ".getBytes();

			os.write(byte_array);
			os
					.write("Name, #chartSymbols, [chartSymbol]*, SymbolYahoo, Amount, Invest, BuyDate, show in yahoo, [Display in ChartOverviews]*\n"
							.getBytes());
			Vector stockVec = _myStore.getStocksVector();
			StockBean stock = null;
			for (int i = 0; i < stockVec.size(); i++) {
				stock = (StockBean) stockVec.elementAt(i);
				os.write(stock.getName().getBytes());
				os.write(("," + stock.getChartSymbols().length).getBytes());
				for (int j=0; j<stock.getChartSymbols().length; j++) {
					os.write((","+stock.getChartSymbol(j)).getBytes());
				}
				//os.write(("," + stock.getSymbolRT()).getBytes());
				//os.write(("," + stock.getSymbolTS()).getBytes());
				os.write(("," + stock.getSymbolYahoo()).getBytes());
				//os.write(("," + stock.getSymbolFt()).getBytes());
				os.write(("," + stock.getAmount()).getBytes());
				os.write(("," + stock.getInvest()).getBytes());
				os.write(("," + Utils.convertDate2String(stock.getBuyDate()))
						.getBytes());
				os.write((","+stock.getShowInYahoo()).getBytes());
				os.write((","
						+ Utils.convertDisplayFlags2String(stock
								.getDisplayFlags()) + "\n").getBytes());
			}
			os.flush();
			_fm.showExportSuccess();
		} catch (IOException e) {
			RTMidlet.getInstance().alert("Error", e.getMessage(), Configuration.ALERT_WAIT_TIME);
			e.printStackTrace();
		} finally {
			try {
				if (os != null)
					os.close();
				if (fileCon != null)
					fileCon.close();

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	protected void exportConfigToCSV() {
		OutputStream os = null;
		FileConnection fileCon = null;
		String url = "file:///" + Configuration.exportPath
				+ "RTMidletConfig.txt";
		try {
			Connection logCon = Connector.open(url, Connector.READ_WRITE);
			fileCon = (FileConnection) logCon;
			if (fileCon == null)
				throw new IOException("Couldn't open url " + url);
			if (!fileCon.exists()) {

				fileCon.create();
				System.out.println("writable: " + fileCon.canWrite());
			} else {
				fileCon.truncate(0);
				System.out.println("truncate: " + fileCon.getPath());
			}

			os = fileCon.openOutputStream();// openOutputStream();
			byte[] byte_array = "# data exported in format <param>=<value>:\n".getBytes();
			
			os.write(("link1=" + Configuration.link1+"\n").getBytes());
			os.write(("link2=" + Configuration.link2+"\n").getBytes());
			for (int i=0; i<Configuration.CHART_URLS.length; i++) {
				os.write(("chartType" +i+"=" + Configuration.getAvailableChartTypes()[i]+"\n").getBytes());
				os.write(("chartUrl" +i+"=" + Configuration.CHART_URLS[i]+"\n").getBytes());
			}
			for (int i=0; i<Configuration.IB_QUERIES.length; i++) {
				os.write(("IBQuery" +i+"=" + Configuration.IB_QUERIES[i]+"\n").getBytes());
			}
			
			os.write(("timeOffset=" + Configuration.timeOffset+"\n").getBytes());
			os.write(("urlIB=" + Configuration.urlIB+"\n").getBytes());
			os.write(("IB_TOKEN=" + Configuration.IB_TOKEN+"\n").getBytes());
			//os.write(("IB_QUERY=" + Configuration.IB_QUERY_TODAY+"\n").getBytes());
			os.write(("exportPath=" + Configuration.exportPath+"\n").getBytes());
			os.flush();
			_fc.showExportSuccess();
		} catch (IOException e) {
			RTMidlet.getInstance().alert("Error", e.getMessage(), Configuration.ALERT_WAIT_TIME);
			e.printStackTrace();
		} finally {
			try {
				if (os != null)
					os.close();
				if (fileCon != null)
					fileCon.close();

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

}
